package com.mju.byc.config;

import com.mju.byc.dao.PermissionRepository;
import com.mju.byc.entity.Permission;
import com.mju.byc.entity.Role;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    // @Autowired
    PermissionRepository permissionRepository;
    CustomFilterInvocationSecurityMetadataSource(PermissionRepository permissionRepository){
        this.permissionRepository = permissionRepository;
    }
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        String requestUrl = ((FilterInvocation) object).getRequestUrl();//admin/hello
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        List<Permission> permissions = permissionRepository.findAll();/// admin/**   dba/**   user/**
        for (Permission permission: permissions){
            if(antPathMatcher.match(permission.getName(),requestUrl)){
                List<Role> roles = permission.getRoles();
                String [] rolestr = new String[roles.size()];
                for (int i = 0; i < roles.size(); i++) {
                    rolestr[i] = roles.get(i).getName();
                    System.out.println(rolestr[i]);
                }
                return SecurityConfig.createList(rolestr);//可以访问这个url的所有的角色
            }
        }
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
}
